package com.atguigu.tingshu.user.strategy.impl;

import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.model.user.UserPaidAlbum;
import com.atguigu.tingshu.user.mapper.UserPaidAlbumMapper;
import com.atguigu.tingshu.user.strategy.ProcessDiffPayRecord;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

/**
 * Description:
 *
 * @author Yanxinhao on 2025/2/13
 */
@Component(value = "1001")
@Slf4j
public class ProcessAlbumTypePayRecord implements ProcessDiffPayRecord {

    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;


    /**
     * 处理消费类型是购买专辑的
     * 且用户成功支付的后置操作
     * @param userPaidRecordVo 用户支付记录
     */
    @Override
    public void processPayRecord(UserPaidRecordVo userPaidRecordVo) {

        String orderNo = userPaidRecordVo.getOrderNo();

        //在往表中插入数据之前,前去表中查一次数据,防止重复插入
        LambdaQueryWrapper<UserPaidAlbum> wrapper = new LambdaQueryWrapper<>();
        UserPaidAlbum userPaidAlbumFromDB = userPaidAlbumMapper.selectOne(wrapper.eq(UserPaidAlbum::getOrderNo, orderNo));
        if (userPaidAlbumFromDB != null){
            throw new GuiguException(201,"user_paid_album表中已存在一条相同数据");
        }

        //向user_paid_album表中插入数据,即用户购买的专辑表
        UserPaidAlbum userPaidAlbum = new UserPaidAlbum();
        userPaidAlbum.setOrderNo(orderNo);
        userPaidAlbum.setUserId(userPaidRecordVo.getUserId());
        userPaidAlbum.setAlbumId(userPaidRecordVo.getItemIdList().get(0));

        int count = userPaidAlbumMapper.insert(userPaidAlbum);
        log.info("保存订单：{}，记录支付流水:{}", orderNo, count >= 1 ? "成功" : "失败");

    }
}